package com.example.springbootoauth2jwtclientserver.exception;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class WenExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResponse handleBindException(MethodArgumentNotValidException ex){
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR,fieldError.getDefaultMessage()));
    }

    @ExceptionHandler(BindException.class)
    public AjaxResponse handleBindException(BindException ex){
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, fieldError.getDefaultMessage()));
    }

    @ExceptionHandler(CustomException.class)
    public AjaxResponse customException(CustomException ex){
        if (ex.getCode() == CustomExceptionType.SYSTEM_ERROR.getCode()) {

        }
        return AjaxResponse.error(ex);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResponse accessDeniedException(AccessDeniedException ex){
        return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, ex.getClass().getName()));
    }

    @ExceptionHandler(Exception.class)
    public AjaxResponse exception(Exception ex){
        return AjaxResponse.error(new CustomException(CustomExceptionType.OTHER_ERROR,"未知异常"));
    }
}
